import { ref } from "vue";

function useBattery (autoStart) {
	
	const charging = ref();
	const level = ref();
	const chargingTime = ref();
	const dischargingTime = ref();
	
	function start() {
		navigator.getBattery().then(battery => {
			charging.value = battery.charging;
			level.value = battery.level;
			chargingTime.value = battery.chargingTime;
			dischargingTime.value = battery.dischargingTime;
			battery.addEventListener('chargingchange', chargingchange);
			battery.addEventListener('levelchange', levelchange);
			battery.addEventListener('chargingtimechange', chargingtimechange);
			battery.addEventListener('dischargingtimechange', dischargingtimechange);
		})
	}
	
	function stop() {
		navigator.getBattery().then(battery => {
			battery.removeEventListener('chargingchange', chargingchange);
			battery.removeEventListener('levelchange', levelchange);
			battery.removeEventListener('chargingtimechange', chargingtimechange);
			battery.removeEventListener('dischargingtimechange', dischargingtimechange);
		})
	}
	
	function chargingchange(e) {
		charging.value = e.target.charging;
	}
	
	function levelchange() {
		level.value = e.target.level;
	}
	
	function chargingtimechange() {
		chargingTime.value = e.target.chargingTime;
	}
	
	function dischargingtimechange() {
		dischargingTime.value = e.target.dischargingTime;
	}
	
	if (autoStart) {
		start();
	}
	
	return {
		charging, level, chargingTime, dischargingTime,
		start, stop
	}
	
}

export default useBattery;